package com.wenwei.paper.activity;

import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.uuzuche.lib_zxing.activity.CaptureFragment;
import com.uuzuche.lib_zxing.activity.CodeUtils;
import com.wenwei.paper.R;
import com.wenwei.paper.base.BaseActivity;
import com.wenwei.paper.base.Constant;
import com.wenwei.paper.bean.OpenDeviceBean;
import com.wenwei.paper.bean.UserLoginBean;
import com.wenwei.paper.net.ApiDeviceManager;
import com.wenwei.paper.net.BaseSubscriber;
import com.wenwei.paper.utils.RogerSPUtils;

import java.util.concurrent.TimeUnit;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import rx.Observable;
import rx.functions.Action1;

/**
 * Created by Administrator on 2017/7/11.
 */
public class QRcodeActivity extends BaseActivity {

    @Bind(R.id.base_title)
    TextView baseTitle;
    private CaptureFragment captureFragment;

    ProgressDialog loadDialog;

    @Override
    public int setLayoutResourceId() {
        return R.layout.activity_qr_code;
    }

    public static boolean isOpen = false;

    @Override
    protected void initView() {
        super.initView();
        baseTitle.setText("扫一扫");
//        StatusBarUtil.setTransparent(QRcodeActivity.this);
//        StatusBarUtil.setTranslucent(QRcodeActivity.this, 1);
        captureFragment = new CaptureFragment();
        // 为二维码扫描界面设置定制化界面
        CodeUtils.setFragmentArgs(captureFragment, R.layout.my_camera);
        captureFragment.setAnalyzeCallback(analyzeCallback);
        getSupportFragmentManager().beginTransaction().replace(R.id.fl_my_container, captureFragment).commit();


        LinearLayout linearLayout = (LinearLayout) findViewById(R.id.linear1);
        linearLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!isOpen) {
                    CodeUtils.isLightEnable(true);
                    isOpen = true;
                } else {
                    CodeUtils.isLightEnable(false);
                    isOpen = false;
                }

            }
        });

        LinearLayout linearLayout2 = (LinearLayout) findViewById(R.id.linear2);
        linearLayout2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                goActivity(mContext, InputCodeActivity.class);

            }
        });
    }


    /**
     * 二维码解析回调函数
     */
    CodeUtils.AnalyzeCallback analyzeCallback = new CodeUtils.AnalyzeCallback() {
        @Override
        public void onAnalyzeSuccess(Bitmap mBitmap, String result) {
//            Intent resultIntent = new Intent();
//            Bundle bundle = new Bundle();
//            bundle.putInt(CodeUtils.RESULT_TYPE, CodeUtils.RESULT_SUCCESS);
//            bundle.putString(CodeUtils.RESULT_STRING, result);
//            resultIntent.putExtras(bundle);
            try{
                String s = result.substring(result.indexOf("=")+1,result.length());
                openDevice(s);
            }catch (Exception e){}
        }

        @Override
        public void onAnalyzeFailed() {
            Intent resultIntent = new Intent();
            Bundle bundle = new Bundle();
            bundle.putInt(CodeUtils.RESULT_TYPE, CodeUtils.RESULT_FAILED);
            bundle.putString(CodeUtils.RESULT_STRING, "");
            resultIntent.putExtras(bundle);

        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    @OnClick(R.id.base_back)
    public void onViewClicked() {
        finish();
    }

    private BaseSubscriber<OpenDeviceBean> openSubscriber;
    private void openDevice(String deviceId){
        openSubscriber = new BaseSubscriber<OpenDeviceBean>(mContext,true,"请稍后...") {
            @Override
            public void onSuccess(final OpenDeviceBean openDeviceBean) {

                loadDialog = new ProgressDialog(mContext);
                loadDialog.setMessage("正在执行开柜，请耐心等待...");
                loadDialog.setCanceledOnTouchOutside(false);
                loadDialog.show();
                Observable.just("").delay(15, TimeUnit.SECONDS).subscribe(new Action1<String>() {
                    @Override
                    public void call(String s) {
                        hasOpenDevice(openDeviceBean.getDeviceid(),openDeviceBean.getlog_id());
                    }
                });

            }

            @Override
            public void onError(Throwable e) {
                super.onError(e);
                if(loadDialog!=null){
                    loadDialog.dismiss();
                }
                finish();
            }
        };
        ApiDeviceManager.getInstance().openDevice(openSubscriber,deviceId);
    }

    //是否打开柜子
    private BaseSubscriber<OpenDeviceBean> hasOpenSubscriber;
    private void hasOpenDevice(final String id, String log){
        hasOpenSubscriber = new BaseSubscriber<OpenDeviceBean>(mContext) {
            @Override
            public void onSuccess(OpenDeviceBean openDeviceBean) {
                loadDialog.dismiss();
                if(getIntent().getIntExtra("type",0) == 1){
                    goActivity(mContext,OperationSuccessActivity.class);
                }else if (getIntent().getIntExtra("type",0) == 2){
                    Bundle bundle = new Bundle();
                    bundle.putString("deviceId",id);
                    goActivity(mContext,ReplenishmentActivity.class,bundle);
                }
                finish();
            }

            @Override
            public void onError(Throwable e) {
                super.onError(e);
                if(loadDialog!=null){
                    loadDialog.dismiss();
                }
                finish();
            }
        };
        ApiDeviceManager.getInstance().hasOpenDevice(hasOpenSubscriber,id,log);
    }
}
